import type { AppRouteRecordRaw } from '@/types/router'
import type { MenuItem } from './Menu.vue'

/**
 * 菜单数据适配器
 * 用于将路由数据转换为菜单数据，实现路由与菜单的解耦
 */
export class MenuAdapter {
  /**
   * 将路由数据转换为菜单数据
   * @param routes 路由数据
   * @returns 菜单数据
   */
  static fromRoutes(routes: AppRouteRecordRaw[]): MenuItem[] {
    return routes
      .filter((route) => !route.meta?.hidden)
      .map((route) => this.convertRouteToMenuItem(route))
  }

  /**
   * 将单个路由转换为菜单项
   * @param route 路由对象
   * @returns 菜单项
   */
  private static convertRouteToMenuItem(route: AppRouteRecordRaw): MenuItem {
    const menuItem: MenuItem = {
      id: route.name || route.path,
      title: route.meta?.title || route.name || route.path,
      icon: route.meta?.icon,
      path: route.path,
      disabled: route.meta?.disabled || false,
      hidden: route.meta?.hidden || false
    }

    // 处理子路由
    if (route.children && route.children.length > 0) {
      menuItem.children = route.children
        .filter((child) => !child.meta?.hidden)
        .map((child) => this.convertRouteToMenuItem(child))
    }

    return menuItem
  }

  /**
   * 将后端菜单数据转换为菜单数据
   * @param backendMenus 后端菜单数据
   * @returns 菜单数据
   */
  static fromBackendMenus(backendMenus: any[]): MenuItem[] {
    return backendMenus
      .filter((menu) => !menu.hidden)
      .map((menu) => this.convertBackendMenuToMenuItem(menu))
  }

  /**
   * 将单个后端菜单转换为菜单项
   * @param menu 后端菜单对象
   * @returns 菜单项
   */
  private static convertBackendMenuToMenuItem(menu: any): MenuItem {
    const menuItem: MenuItem = {
      id: menu.id || menu.menuId || menu.name,
      title: menu.title || menu.menuName || menu.name || '',
      icon: menu.icon || menu.menuIcon,
      path: menu.path || menu.menuRoute || menu.routePath || menu.url || '',
      disabled: menu.disabled || false,
      hidden: menu.hidden || false
    }

    // 处理子菜单
    if (menu.children && menu.children.length > 0) {
      menuItem.children = menu.children
        .filter((child: any) => !child.hidden)
        .map((child: any) => this.convertBackendMenuToMenuItem(child))
    }

    return menuItem
  }

  /**
   * 创建自定义菜单数据
   * @param menuData 自定义菜单数据
   * @returns 菜单数据
   */
  static fromCustomData(menuData: any[]): MenuItem[] {
    return menuData.map((item) => this.convertCustomDataToMenuItem(item))
  }

  /**
   * 将自定义数据转换为菜单项
   * @param item 自定义数据项
   * @returns 菜单项
   */
  private static convertCustomDataToMenuItem(item: any): MenuItem {
    const menuItem: MenuItem = {
      id: item.id || item.key || item.name,
      title: item.title || item.label || item.name || '',
      icon: item.icon,
      path: item.path || item.key || '',
      url: item.url,
      disabled: item.disabled || false,
      hidden: item.hidden || false
    }

    // 处理子项
    if (item.children && item.children.length > 0) {
      menuItem.children = item.children.map((child: any) => this.convertCustomDataToMenuItem(child))
    }

    return menuItem
  }
}
